package com.yudedu.hospital.controller;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yudedu.hospital.entity.Appointment;
import com.yudedu.hospital.entity.BranchCourts;
import com.yudedu.hospital.entity.CaseHistery;
import com.yudedu.hospital.entity.Department;
import com.yudedu.hospital.entity.Doctor;
import com.yudedu.hospital.entity.User;
import com.yudedu.hospital.entity.UserLogin;
import com.yudedu.hospital.service.UserService;

@Controller
public class IndexController {

	@Resource
	UserService userService;
	private UserLogin user;
	private List<CaseHistery> caseHistery;
	private List<Appointment> appointment;
	private User userMsg;
	
	

//	@RequestMapping("index")
//	public Object index(@Valid UserLogin user, BindingResult br, Model model) {
//		if (br.hasErrors()) {
//			List<ObjectError> error = br.getAllErrors();
//			for (ObjectError err : error) {
//				DefaultMessageSourceResolvable pro = (DefaultMessageSourceResolvable) err.getArguments()[0];
//				System.out.println(pro.getCode());
//				System.out.println(err.getDefaultMessage());
//				model.addAttribute(pro.getCode() + "Msg", err.getDefaultMessage());
//				// 用于后端验证
//			}
//
//			return "login";
//		}
//		model.addAttribute("hello", user); // 表单提交user数据，在index页面上显示
//		return userService.query();
//	}
	
	
	@RequestMapping("index")
	public Object index( UserLogin user, Model model) {
		model.addAttribute("hello", user); // 表单提交user数据，在index页面上显示
		return userService.query();
	}
	
	

	@RequestMapping("login")
	public Object login() {
		return "login";
	}
	
	@RequestMapping("noauth")
	public Object noauth() {
		return "noauth";
	}
	
	@RequestMapping("page")
	public Object page() {
		return "page";
	}

	@RequestMapping("register")
	public Object register() {
		return "register";
	}

//	@RequestMapping("doRegister")
//	public Object doRegister(@Valid UserLogin user, BindingResult br,String username, String password, Model model) {
//		if (br.hasErrors()) {
//			List<ObjectError> error = br.getAllErrors();
//			for (ObjectError err : error) {
//				DefaultMessageSourceResolvable pro = (DefaultMessageSourceResolvable) err.getArguments()[0];
//				System.out.println(pro.getCode());
//				System.out.println(err.getDefaultMessage());
//				model.addAttribute(pro.getCode() + "Msg", err.getDefaultMessage());
//			}
//			return "register"; // 如果有输入信息不符合要求就返回到注册界面
//		} // 否则就进行注册的数据操作
//		UserLogin testUser = userService.query(username, password);
//		if (testUser==null) {
//			userService.register(username,password);
//			String alert="注册成功！请选择登录！";
//			model.addAttribute("alert",alert);
//			return "register";
//		}else {
//			String alert="用户已存在！请选择登录或重新注册！";
//			model.addAttribute("alert",alert);
//			return "register";
//		}
//	}
	
	
	@RequestMapping("doRegister")
	public Object doRegister(String username, String password, Model model) {
		if (username.length()<6 ||password.length()<6) {
			System.out.println("duanle");
			model.addAttribute("alert", "账户或密码不能小于六位数");
			return "register";
		}
		UserLogin testUser = userService.query(username, password);
		if (testUser==null) {
			userService.register(username,password);
			String alert="注册成功！请选择登录！";
			model.addAttribute("alert",alert);
			return "register";
		}else {
			String alert="用户已存在！请选择登录或重新注册！";
			model.addAttribute("alert",alert);
			return "register";
		}
	}

	@RequestMapping("caseHistery")
	public Object caseHistery(HttpServletRequest request,Integer pageNumber,Model model) {
		if (pageNumber==null) {
			pageNumber=1;
		}
		PageHelper.startPage(pageNumber,3);
		UserLogin loginMessage = (UserLogin) request.getSession().getAttribute("loginMessage");
		caseHistery = userService.queryCaseHistery(loginMessage.getId());
		System.out.println(caseHistery);
//		request.getSession().setAttribute("caseHistery", caseHistery);
		
		PageInfo page = new PageInfo(caseHistery);
		model.addAttribute("caseHistery", caseHistery);
		model.addAttribute("pageNumber", page.getPageNum());
		model.addAttribute("pages", page.getPages());
		return "caseHistery";
		
	}

	@RequestMapping("info")
	public Object info() {
		return "info";
	}

	@RequestMapping("deleCaseHistery")
	public Object deleCaseHistery(HttpServletRequest request, int id,Model model) {
		System.out.println(id);
		userService.deleCaseHistery(id);
		UserLogin loginMessage = (UserLogin) request.getSession().getAttribute("loginMessage");
		request.getSession().removeAttribute("caseHistery");
		caseHistery = userService.queryCaseHistery(loginMessage.getId());
		request.getSession().setAttribute("caseHistery", caseHistery);
		model.addAttribute("scc", "true");
		model.addAttribute("url", "caseHistery");

		return "tips";
	}

	@RequestMapping("deleAppointment")
	public Object deleAppointment(HttpServletRequest request, int id) {
		System.out.println(id);
		userService.deleAppointment(id);
		request.getSession().removeAttribute("appointment");
		appointment = userService.queryAppointment(user.getId());
		request.getSession().setAttribute("appointment", appointment);

		return "info";
	}

	@RequestMapping("personal")
	public Object personal(HttpServletRequest request) {
			user=(UserLogin) request.getSession().getAttribute("loginMessage");
			userMsg = userService.queryMsg(user.getId());
			System.out.println(user.getId());
			request.getSession().setAttribute("userMessage", userMsg);
			// 将用户信息保存到session中
			return "personal";
		
	}

	@RequestMapping("editPersonal")
	public Object editPersonal(HttpServletRequest request,Model model) {
//		if (br.hasErrors()) {
//			List<ObjectError> error = br.getAllErrors();
//			for (ObjectError err : error) {
//				DefaultMessageSourceResolvable pro = (DefaultMessageSourceResolvable) err.getArguments()[0];
//				System.out.println(pro.getCode());
//				System.out.println(err.getDefaultMessage());
//				model.addAttribute(pro.getCode() + "Msg", err.getDefaultMessage());
//				// 用于后端验证,用于刷新页面的方式
//			}
//			return "login";
//		}
//			Map<String,String> errors= new HashMap<>();
//			if (br.hasErrors()) {
//				List<ObjectError> error = br.getAllErrors();
//				for (ObjectError err : error) {
//					DefaultMessageSourceResolvable pro = (DefaultMessageSourceResolvable) err.getArguments()[0];
//					System.out.println(pro.getCode());
//					System.out.println(err.getDefaultMessage());
//					errors.put(pro.getCode() + "Msg", err.getDefaultMessage());
//					// 用于后端验证,用于ajax提交的方式
//				}
//
//				return errors;
//			}
		
//		if (user==null) {
//			return "login";
//		}else {
//			userMsg = userService.queryMsg(user.getId());
//			request.getSession().setAttribute("userMessage", userMsg);
//			// 将用户信息保存到session中
			return "editPersonal";
//			
//		}
	}
	
	
//	@ExceptionHandler     //异常处理，所有的异常都会到这里——统一处理
//	@ResponseBody
//	public Object formValid (Exception ex) {
//		if (ex instanceof BindException) {
//			Map<String,String> errors= new HashMap<>();
//		    BindException br = (BindException)ex;
//			if (br.hasErrors()) {
//				List<ObjectError> error = br.getAllErrors();
//				for (ObjectError err : error) {
//					DefaultMessageSourceResolvable pro = (DefaultMessageSourceResolvable) err.getArguments()[0];
//					System.out.println(pro.getCode());
//					System.out.println(err.getDefaultMessage());
//					errors.put(pro.getCode() + "Msg", err.getDefaultMessage());
//				}
//
//				return errors;
//			}
//		}
//		
//		return "0";
//	}
	
	
	

	@RequestMapping("doEditPersonal")
	public Object doEditPersonal(String name, String sex, String idCard, String birthday, String userPhone,
			String lgAddress, String smAddress, String QQ, String zipCode, String email,HttpServletRequest request) {
		System.out.println(name);
		System.out.println(sex);
		System.out.println(idCard);
		System.out.println(birthday);
		System.out.println(userPhone);
		System.out.println(lgAddress);
		System.out.println(smAddress);
		System.out.println(QQ);
		System.out.println(zipCode);
		System.out.println(email);
		String Address = lgAddress + smAddress;
		System.out.println(Address); // 显示完整地址
		String removeStr = "/";
		String address = Address.replace(removeStr, ""); // 去掉省市区中的"/"
		// user = userService.query();
		int user_id = user.getId();
		System.out.println(user.getId());
		User Msg = userService.queryMsg(user_id);
		if (Msg==null) {
			userService.insertUserMessage(user_id, name, sex, idCard, birthday, userPhone, address, QQ, zipCode, email);
		}else {
			userService.editUserMessage(user_id, name, sex, idCard, birthday, userPhone, address, QQ, zipCode, email);
		}
		
		
		userMsg = userService.queryMsg(user.getId());
		request.getSession().setAttribute("userMessage", userMsg);
		return "personal";
	}


	@RequestMapping("testCaseHistery")
	@ResponseBody
	public Object testCaseHistery(HttpServletRequest request) {
		if (user == null) {
			return "login";
		} else {
			int user_id = user.getId();
			caseHistery = userService.queryCaseHistery(user_id);
			System.out.println(caseHistery);
			request.getSession().setAttribute("caseHistery", caseHistery);
			// 把病历保存在session中，方便拿值
			return caseHistery;
		}
	}
//
//	@RequestMapping("testAppointment")
//	public Object testAppointment(HttpServletRequest request) {
//		if (user == null) {
//			return "login";
//		} else {
//			int user_id = user.getUser().getId();
//			appointment = userService.queryAppointment(user_id);
//			System.out.println(appointment);
//			request.getSession().setAttribute("appointment", appointment);
//			// 把病历保存在session中，方便拿值
//			return "testAppointment";
//		}
//	}

	@RequestMapping("editPassword")
	public Object editPassword() {
		return "editPassword";
	}

	@RequestMapping("doEditPassword")
	public Object editPassword(HttpSession session, String renewpass,Model model) {
		System.out.println(renewpass);
		UserLogin editSession = (UserLogin) session.getAttribute("loginMessage"); // 在session中拿到数组
		userService.editPassword(renewpass, editSession.getId()); // 对象中拿值
		String alert = "修改密码成功！";
		model.addAttribute("alert", alert);
		return "editPassword";
	}

	
	@RequestMapping("Submit")
	public Object Submit() {
		return "Submit";
	}
	
	@RequestMapping("outlogin")
	public Object outlogin() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "redirect:index";
	}
	
	
	@RequestMapping("doEdit")
	public Object doEdit(int id,HttpServletRequest request,HttpServletResponse response,String hospitalName,String address,String tele,String departments,String doctor,String date,String email,String doctorTele) throws ServletException, IOException {
		userService.editAppointment(id,hospitalName,address,tele,departments,doctor,date,email,doctorTele);
		
		UserLogin loginMessage = (UserLogin) request.getSession().getAttribute("loginMessage");
		int user_id = loginMessage.getId();
		request.getSession().removeAttribute("appointment");
		appointment = userService.queryAppointment(user_id);
		request.getSession().setAttribute("appointment", appointment);
		return "info";
	}
	
	@RequestMapping("editAppointment")
	public Object editAppointment(int id,HttpServletRequest request,Model model) {
		List<Appointment> editAppointment = (List<Appointment>) request.getSession().getAttribute("appointment");
		model.addAttribute("editId", id);                 //把id传到jsp页面，进行隐藏域传值
		model.addAttribute("editAppointment", editAppointment);
		return "editAppointment";
	}
	
	
	@RequestMapping("doAppointment")
	public Object doAppointment(HttpServletRequest request,String hospitalName,String address,String tele,String departments,String doctor,String date,String email,String doctorTele) {
		UserLogin loginMessage = (UserLogin) request.getSession().getAttribute("loginMessage");
		int user_id = loginMessage.getId();
		userService.addAppointment(hospitalName,address,tele,departments,doctor,date,email,doctorTele,user_id);
		request.getSession().removeAttribute("appointment");
		appointment = userService.queryAppointment(user_id);
		request.getSession().setAttribute("appointment", appointment);
		return "info";
	}
	
	@RequestMapping("ajax")
	@ResponseBody
	public Object ajax(String pa,HttpServletRequest request) {
		System.out.println(pa+"---");
		List<BranchCourts> branchCourts = userService.querybranchCourts(pa);
		System.out.println(branchCourts);
		return branchCourts;
	}
	
	@RequestMapping("ajax1")
	@ResponseBody
	public Object ajax1(Integer branch_id,Integer depart_id,HttpServletRequest request) {
		System.out.println(branch_id+"---");
		System.out.println(depart_id+"---");
		List<Doctor> doctors = userService.queryDoctor(branch_id,depart_id);
		System.out.println(doctors);
		return doctors;
	}
	
	@RequestMapping("ajax2")
	@ResponseBody
	public Object ajax2(int doctor_id,HttpServletRequest request) {
		System.out.println(doctor_id+"~~~~~~~");
		List<Doctor> doctor = userService.queryDoctor(doctor_id);
		System.out.println(doctor+"22222222");
		return doctor;
	}

	@RequestMapping("doLogin")
	public Object login(String username, String password, Model model, HttpServletRequest request) { // form提交，login和password可以直接拿到
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username,password);
		try {
			subject.login(token);
		} catch (UnknownAccountException uae) {
			model.addAttribute("error","账号不存在");
			model.addAttribute("data","账号username");
			return "login";
			
		} catch (IncorrectCredentialsException ice) {
			model.addAttribute("error","账号不存在");
			model.addAttribute("data","账号username");
			return "login";
		}
		
		
		
		
			user = userService.login(username, password);
		
			request.getSession().setAttribute("loginMessage", user);
			// 把登录信息保存到session中
			model.addAttribute("user", user);

			appointment = userService.queryAppointment(user.getId());    	 //所有预约
			request.getSession().setAttribute("appointment", appointment);
			
			List<BranchCourts> branchCourts = userService.querybranchCourts();		//拿到所有分院信息
			request.getSession().setAttribute("branchCourts", branchCourts);
			
			List<Department> department = userService.queryDepartment();
			System.out.println(department);
			request.getSession().setAttribute("department",department);
			
			User userMsg = userService.queryMsg(user.getId());
			request.getSession().setAttribute("userMessage", userMsg);
			
			return "redirect:index";
		
	}
	
}
